package com.jsoft.jsofted.framework.mybatis;

import com.baomidou.mybatisplus.core.conditions.AbstractWrapper;
import com.baomidou.mybatisplus.core.conditions.SharedString;
import com.baomidou.mybatisplus.core.conditions.query.Query;
import com.baomidou.mybatisplus.core.conditions.segments.MergeSegments;
import com.baomidou.mybatisplus.core.metadata.TableFieldInfo;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import com.baomidou.mybatisplus.core.toolkit.ArrayUtils;
import com.baomidou.mybatisplus.core.toolkit.StringPool;

import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Predicate;

public class CocQueryWrapper<T> extends AbstractWrapper<T, String, CocQueryWrapper<T>>
        implements Query<CocQueryWrapper<T>, T, String> {

    /**
     * 查询字段
     */
    private final SharedString sqlSelect = new SharedString();

    public CocQueryWrapper() {
        this(null);
    }

    public CocQueryWrapper(T entity) {
        super.setEntity(entity);
        super.initNeed();
    }

    public CocQueryWrapper(T entity, String... columns) {
        super.setEntity(entity);
        super.initNeed();
        this.select(columns);
    }

    /**
     * 非对外公开的构造方法,只用于生产嵌套 sql
     *
     * @param entityClass 本不应该需要的
     */
    private CocQueryWrapper(T entity, Class<T> entityClass, AtomicInteger paramNameSeq,
                            Map<String, Object> paramNameValuePairs, MergeSegments mergeSegments,
                            SharedString lastSql, SharedString sqlComment, SharedString sqlFirst) {
        super.setEntity(entity);
        super.setEntityClass(entityClass);
        this.paramNameSeq = paramNameSeq;
        this.paramNameValuePairs = paramNameValuePairs;
        this.expression = mergeSegments;
        this.lastSql = lastSql;
        this.sqlComment = sqlComment;
        this.sqlFirst = sqlFirst;
    }

    @Override
    public CocQueryWrapper<T> select(String... columns) {
        if (ArrayUtils.isNotEmpty(columns)) {
            this.sqlSelect.setStringValue(String.join(StringPool.COMMA, columns));
        }
        return typedThis;
    }

    @Override
    public CocQueryWrapper<T> select(Class<T> entityClass, Predicate<TableFieldInfo> predicate) {
        super.setEntityClass(entityClass);
        this.sqlSelect.setStringValue(TableInfoHelper.getTableInfo(getEntityClass()).chooseSelect(predicate));
        return typedThis;
    }

    @Override
    public String getSqlSelect() {
        return sqlSelect.getStringValue();
    }

    public CocQueryWrapper regexp(String column, String val) {
        return doIt(true,
                () -> column,
                () -> "regexp",
                () -> formatSql("{0}", val)
        );
    }

    /**
     * 函数调用的子查询
     *
     * @param column     字段名，如： org_id
     * @param op         数据库操作符，如：正则表达式操作 regexp
     * @param subSelect 函数调用格式，如：函数子查询 getOrgTreeIds({0})；
     *                  SQL语句子查询 select role_id from sys_role_perm where menu_id eq {0}；
     * @param subParams 函数所需参数清单
     */
    public CocQueryWrapper subSelect(String column, String op, String subSelect, Object... subParams) {
        return doIt(true,
                () -> column,
                () -> op,
                () -> formatSql(subSelect, subParams)
        );
    }

    /**
     * 用于生成嵌套 sql
     * <p>
     * 故 sqlSelect 不向下传递
     * </p>
     */
    @Override
    protected CocQueryWrapper<T> instance() {
        return new CocQueryWrapper<>(getEntity(), getEntityClass(), paramNameSeq, paramNameValuePairs, new MergeSegments(),
                SharedString.emptyString(), SharedString.emptyString(), SharedString.emptyString());
    }

    @Override
    public void clear() {
        super.clear();
        sqlSelect.toNull();
    }
}